package com.lsl.adskip.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;


import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.lsl.adskip.MainActivity;
import com.lsl.adskip.R;
import com.lsl.adskip.entity.RuleDetail;
import com.lsl.adskip.entity.RuleEntity;
import com.lsl.adskip.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyService extends AccessibilityService {
    private static MyService instance;
    public static boolean serviceState = false;
    public static boolean dialogAD = false;
    public static boolean superMode = false;
    private ExecutorService executor = Executors.newFixedThreadPool(4);
    private List<RuleEntity> reluList;

    public static boolean isServiceEnable() {
        return instance != null;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (serviceState) {
            if (event != null) {
                //跳过广告逻辑
                Log.d("监听中", "开屏广告");
                AccessibilityNodeInfo currentNodeInfo = getCurrentRootNode();
                if (currentNodeInfo != null) {
                    List<AccessibilityNodeInfo> skipBtnNodes = currentNodeInfo.findAccessibilityNodeInfosByText("跳过");
                    List<AccessibilityNodeInfo> closeBtnNodes = currentNodeInfo.findAccessibilityNodeInfosByText("关闭");
                    if (closeBtnNodes != null && !closeBtnNodes.isEmpty()) {
                        AccessibilityNodeInfo ad = closeBtnNodes.get(0);
                        Log.d("检测到广告节点：", String.valueOf(ad));
                        ad.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    }
                    if (skipBtnNodes != null && !skipBtnNodes.isEmpty()) {
                        AccessibilityNodeInfo ac = skipBtnNodes.get(0);
                        Log.d("检测到广告节点：", String.valueOf(ac));
                        ac.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    }
                }
            }
        }
        //监听弹窗广告
        if (dialogAD) {
            if (event != null) {
                Log.d("监听中", "弹窗广告");
                AccessibilityNodeInfo dialogNodeInfo = getCurrentRootNode();
                if (dialogNodeInfo != null) {
                    String viewId = dialogNodeInfo.getPackageName() + ":id/" + "close";
                    List<AccessibilityNodeInfo> closeNodes = dialogNodeInfo.findAccessibilityNodeInfosByViewId(viewId);
                    if (closeNodes != null && !closeNodes.isEmpty()) {
                        AccessibilityNodeInfo ac = closeNodes.get(0);
                        ac.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }
            }
        }
        if (event != null && superMode) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    if (reluList != null) {
                        for (RuleEntity re : reluList) {
                            for (RuleDetail rd : re.getRules()) {
                                if (searchNode(rd.getId()) != null) {
                                    AccessibilityNodeInfo node = searchNode(rd.getAction());
                                    if (node != null) {
                                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                        Log.d("模式", "超级模式:" + String.valueOf(node));
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onInterrupt() {
        Log.d("服务状态", "断开连接");
    }

    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        Log.d("服务状态", "连接成功");
        ToastUtil.showLongToast(this, "服务已连接");
        //startForeNotification();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                reluList = readJsonToRuleList();
                Log.d("加载", "自定义规则已加载");
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("服务状态", "服务重启");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d("生命周期", "destroy");
        ToastUtil.showLongToast(this, "屏蔽广告服务已被销毁");
        instance = null;
        executor.shutdown();
    }

    private AccessibilityNodeInfo getCurrentRootNode() {
        try {
            return getRootInActiveWindow();
        } catch (Exception e) {
            if (e.getMessage() != null) {
                Log.e("根节点异常", e.getMessage());
            }
            return null;
        }
    }


    /**
     * 读取自定义广告类型JSON文件生成规则实体列表
     */
    public List<RuleEntity> readJsonToRuleList() {
        List<RuleEntity> ruleEntityList = new ArrayList<>();
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.all_rules);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            inputStream.close();
            JSONArray jsonArray = new JSONArray(sb.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Iterator<String> keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    String value = jsonObject.getString(key);
                    JSONObject ruleEntityJson = new JSONObject(value);
                    JSONArray popupRules = ruleEntityJson.getJSONArray("popup_rules");
                    RuleEntity ruleEntity = new RuleEntity();
                    ArrayList<RuleDetail> ruleDetails = new ArrayList<>();
                    for (int j = 0; j < popupRules.length(); j++) {
                        JSONObject ruleObject = popupRules.getJSONObject(j);
                        RuleDetail ruleDetail = new RuleDetail(ruleObject.getString("id"),
                                ruleObject.getString("action"));
                        ruleDetails.add(ruleDetail);
                    }
                    ruleEntity.setRules(ruleDetails);
                    ruleEntityList.add(ruleEntity);
                }
            }
            return ruleEntityList;
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return ruleEntityList;
    }

    /**
     * 匹配广告节点
     * @param filter
     * @return
     */
    private AccessibilityNodeInfo searchNode(String filter) {
        AccessibilityNodeInfo rootNode = getCurrentRootNode();
        if (rootNode != null) {
            List<AccessibilityNodeInfo> nodeInfosByText = rootNode.findAccessibilityNodeInfosByText(filter);
            if (!nodeInfosByText.isEmpty()) {
                return nodeInfosByText.get(0);
            }
            String viewId = rootNode.getPackageName() + ":id/" + filter;
            List<AccessibilityNodeInfo> nodeInfosByViewId = rootNode.findAccessibilityNodeInfosByViewId(viewId);
            if (!nodeInfosByViewId.isEmpty()) {
                return nodeInfosByViewId.get(0);
            }
        }
        return null;
    }


    //private int notificationId = 10;

//    private void startForeNotification() {
//        Context context = this;
//        // 创建通知渠道
//        CharSequence name = "广告监听服务已启动";
//        String description = "如需设置监听类型，点此进入设置";
//        // 创建通知渠道
//        NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
//        channel.setDescription("Channel Description");
//        // 创建通知管理器
//        NotificationManager notificationManager = getSystemService(NotificationManager.class);
//        notificationManager.createNotificationChannel(channel);
//        Intent intent = new Intent(context, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        // 构建通知
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "lis")
//                .setSmallIcon(R.drawable.aircraft)
//                .setContentTitle(name)
//                .setContentText(description)
//                .setContentIntent(pendingIntent)
//                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
//        notificationManager.notify(notificationId, builder.build());
//        // 在服务中的适当位置调用以下方法以显示前台通知
//        startForeground(notificationId, builder.build());
//    }
}
